650E - Clockwork Bomb - CodeForces Solution


data structures dfs and similar dsu greedy trees *3200

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>

using namespace std;

const int N=5e5+5;

struct graph{

	struct edge{int v,next;}e[N<<1];

	int head[N],edgenum,fa[N];

	void add(int u,int v){

		e[++edgenum]=edge{v,head[u]};

		head[u]=edgenum;

	}

	void dfs(int u,int f){

		fa[u]=f;

		for(int i=head[u];i;i=e[i].next)

			if(e[i].v^f)dfs(e[i].v,u);

	}

}g1,g2;

int fa[N],cnt,n;

int find(int x){return fa[x]==x?x:fa[x]=find(fa[x]);}

struct node{int x,y,u,v;}a[N<<1];

void dfs(int u,int fa){

	for(int i=g1.head[u],v;i;i=g1.e[i].next){

		if((v=g1.e[i].v)==fa)continue;

		dfs(v,u);

		if(find(u)^find(v))a[++cnt]={u,v,find(v),g2.fa[find(v)]};

	}

}

int main(){

	scanf("%d",&n);

	for(int i=1,u,v;i<n;i++){

		scanf("%d%d",&u,&v);

		g1.add(u,v);g1.add(v,u);

	}

	for(int i=1,u,v;i<n;i++){

		scanf("%d%d",&u,&v);

		g2.add(u,v);g2.add(v,u);

	}

	g1.dfs(1,0);g2.dfs(1,0);fa[1]=1;

	for(int i=2;i<=n;i++){

		int f=g2.fa[i];

		if(g1.fa[f]==i||g1.fa[i]==f)fa[i]=f;

		else fa[i]=i;

	}

	dfs(1,0);

	printf("%d\n",cnt);

	for(int i=1;i<=cnt;i++)printf("%d %d %d %d\n",a[i].x,a[i].y,a[i].u,a[i].v);

}


Comments

Submit
0 Comments
More Questions

678A - Johny Likes Numbers
1699C - The Third Problem
1697D - Guess The String
754B - Ilya and tic-tac-toe game
760A - Petr and a calendar
1573A - Countdown
166A - Rank List
1631B - Fun with Even Subarrays
727A - Transformation from A to B
822B - Crossword solving
1623A - Robot Cleaner
884B - Japanese Crosswords Strike Back
862B - Mahmoud and Ehab and the bipartiteness
429A - Xor-tree
1675C - Detective Task
950A - Left-handers Right-handers and Ambidexters
672B - Different is Good
1C - Ancient Berland Circus
721A - One-dimensional Japanese Crossword
1715B - Beautiful Array
60B - Serial Time
453A - Little Pony and Expected Maximum
1715A - Crossmarket
1715C - Monoblock
1512C - A-B Palindrome
1679B - Stone Age Problem
402A - Nuts
792A - New Bus Route
221A - Little Elephant and Function
492C - Vanya and Exams